<template>
    <el-dialog v-model="dialogVisible" title="添加身份" width="540">
        <el-form :model="formItem" label-width="80">
            <el-form-item label="身份昵称:">
                <el-input v-model="formItem.name" clearable />
            </el-form-item>
            <el-form-item label="角色状态:">
                <el-radio-group v-model="formItem.state">
                    <el-radio :value='1'>开启</el-radio>
                    <el-radio :value='0'>关闭</el-radio>
                </el-radio-group>
            </el-form-item>
            <el-form-item label="权限:">
                <div style="display: flex;align-items: start; width:100%;">
                    <div style="flex-grow: 1; height: 200px; overflow-y: scroll">
                        <el-tree ref="treeRef" show-checkbox :data="permissionData.rows" node-key="_id"
                            :props="{ label: 'title' }" :check-strictly="true" @check="handleCheckChange" />
                    </div>
                    <el-button type="primary" link @click="treeOpen()">{{ isOpen ? '收起' : '展开' }}</el-button>
                </div>
            </el-form-item>
        </el-form>
        <template #footer>
            <el-button @click="dialogVisible = false">取消</el-button>
            <el-button type="primary" @click="onConfirm">确认</el-button>
        </template>
    </el-dialog>
</template>
<script setup lang="ts">
import { addRoleApi, getRoleByIdApi, updateRoleApi } from '@/api/roleManage';
import { useFindData } from '@/composables/findData';
import { nextTick, ref, useTemplateRef, watch } from 'vue';
const dialogVisible = ref(false);
const formItem = ref<any>({});
const emit = defineEmits(['getRole']);
const treeRef = useTemplateRef('treeRef');
const isOpen = ref(false);
const openDialog = (item?: string) => {
    if (item) {
        getRoleById(item);
    } else {
        formItem.value = {};
    }
    dialogVisible.value = true;
};
const { permissionData, getPermissionJoint, } = useFindData();







// --------------------------- Tree组件的父子联动勾选功能 -----------------------------
// 当用户点击Tree组件中的复选框时，触发该事件
const handleCheckChange = (node: any, checkedStatus: any) => {
    // 判断选中的数组中是否有当前点击的节点
    const checked = checkedStatus.checkedKeys.includes(node._id);
    // 进入if，说明用户当前的操作是【勾选】
    if (checked) {
        // 选中节点时处理子节点和父节点
        if (node.children?.length) {
            // 勾选所有子节点
            checkAllChildren(node, true);
        }
        checkAllParents(node);
    } else {
        // 取消节点时处理子节点
        if (node.children?.length) {
            checkAllChildren(node, false);
        }
    }
}
// 递归操作子节点
const checkAllChildren = (node: any, checked: boolean) => {
    node.children.forEach((child: any) => {
        treeRef.value?.setChecked(child._id, checked, false);
        if (child.children) checkAllChildren(child, checked);
    });
}
// 递归操作父节点
const checkAllParents = (node: any) => {
    let parent = getParentNode(node);
    while (parent) {
        treeRef.value?.setChecked(parent._id, true, false);
        parent = getParentNode(parent);
    }
}
// 父节点查找算法，返回目标节点的直接父节点
const getParentNode = (node: any) => {
    const findParent = (data: any[], targetId: string, parent: any): any => {
        for (const item of data) {
            if (item._id === targetId) return parent;
            if (item.children) {
                const found = findParent(item.children, targetId, item);
                if (found) return found;
            }
        }
        return null;
    }
    return findParent(permissionData.rows, node._id, null);
}
// ------------------------- Tree组件的父子联动勾选功能 --------------------------------









//tree组件的展开收起
function treeOpen() {
    isOpen.value = !isOpen.value;

    const allNodes = treeRef.value?.store._getAllNodes();
    allNodes?.forEach(item => {
        item.expanded = isOpen.value;
    })
}
function addRole() {
    addRoleApi({
        ...formItem.value,
        permissionIds: treeRef.value!.getCheckedKeys(false)
    }).then(res => {
        if (res.code == 200) {
            ElMessage({
                type: 'success',
                message: '添加身份成功',
            });
            emit('getRole');
        } else {
            ElMessage.error(res.message);
        }
    })
}

function updateRole() {
    updateRoleApi({
        ...formItem.value, permissionIds: treeRef.value!.getCheckedKeys(false)
    }).then(res => {
        if (res.code == 200) {
            ElMessage({
                type: 'success',
                message: '修改身份成功',
            });
            emit('getRole')
        } else {
            ElMessage.error(res.message);
        }
    })
}
function getRoleById(_id: string) {
    getRoleByIdApi({ _id }).then(res => {
        console.log(res);
        if (res.code == 200) {
            formItem.value = { ...res.data, permissionIds: res.data.permissionIds }
            nextTick(() => {
                // nextTick内部的箭头函数，会在页面标签组件挂载渲染完成后才执行

                // 调用Tree组件的setCheckedKeys方法，来设置默认选中
                treeRef.value?.setCheckedKeys(formItem.value.permissionIds, false);
            })
        }

    })
}

function onConfirm() {
    if (formItem.value._id) {
        updateRole();
    } else {
        addRole();
    }
    dialogVisible.value = false;
};
defineExpose({
    openDialog
})
watch(dialogVisible, () => {
    getPermissionJoint({ creator: 'zhangjunling', });
})
</script>

<style scoped>
.el-input,
.el-select {
    width: 412px;

}
</style>
<style></style>
